<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="仓库名称" prop="wname">
              <el-input v-model="queryParams.wname" placeholder="请输入仓库名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="ASIN" prop="asin">
              <el-input v-model="queryParams.asin" placeholder="请输入ASIN" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="品名" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入品名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="MSKU" prop="msku">
              <el-input v-model="queryParams.msku" placeholder="请输入MSKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="FNSKU" prop="fnsku">
              <el-input v-model="queryParams.fnsku" placeholder="请输入FNSKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="SKU" prop="sku">
              <el-input v-model="queryParams.sku" placeholder="请输入SKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lingxing:fbaStock:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['lingxing:fbaStock:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['lingxing:fbaStock:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['lingxing:fbaStock:export']">导出</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleSyncData">同步数据</el-button>
          </el-col>
          <el-col :span="15">
            数据更新时间：
            <el-text>{{ newestUpdateTime }}</el-text>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="fbaStockList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="仓库名称" align="center" prop="wname" width="160" />
        <el-table-column label="ASIN" align="center" prop="asin" width="140" />
        <el-table-column label="品名" align="center" prop="productName" width="160" />
        <el-table-column label="MSKU" align="center" prop="msku" width="180" />
        <el-table-column label="FNSKU" align="center" prop="fnsku" width="140" />
        <el-table-column label="SKU" align="center" prop="sku" width="180" />
        <el-table-column label="品牌名称" align="center" prop="brandName" />
        <el-table-column label="货值" align="center" prop="stockCostTotal" />
        <el-table-column label="库存成本" align="center" prop="cost" />
        <el-table-column label="可售" align="center" prop="afnFulfillableQuantity" />
        <el-table-column label="待调仓" align="center" prop="reservedFcTransfers" />
        <el-table-column label="调仓中" align="center" prop="reservedFcProcessing" />
        <el-table-column label="待发货" align="center" prop="reservedCustomerorders" />
        <el-table-column align="center" prop="totalFulfillableQuantity">
          <template #header>
            <span>
              总可用库存
              <el-tooltip effect="dark" content="总可用库存 = 可售+待调仓+调仓中" placement="top-start">
                <svg-icon icon-class="question" />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="不可售" align="center" prop="afnUnsellableQuantity" />
        <el-table-column label="计划入库" align="center" prop="afnInboundWorkingQuantity" />
        <el-table-column label="在途" align="center" prop="afnInboundShippedQuantity" />
        <el-table-column label="入库中" align="center" prop="afnInboundReceivingQuantity" />
        <el-table-column label="实际在途" align="center" prop="afnErpRealShippedQuantity" />
        <!--        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
        <!--          <template #default="scope">-->
        <!--            <el-tooltip content="修改" placement="top">-->
        <!--              <el-button v-hasPermi="['lingxing:fbaStock:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>-->
        <!--            </el-tooltip>-->
        <!--            <el-tooltip content="删除" placement="top">-->
        <!--              <el-button v-hasPermi="['lingxing:fbaStock:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>-->
        <!--            </el-tooltip>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改领星FBA库存对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="fbaStockFormRef" :model="form" :rules="rules" label-width="80px"></el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FbaStock" lang="ts">
import { listFbaStock, getFbaStock, delFbaStock, addFbaStock, updateFbaStock, syncData, getNewestUpdateTime } from '@/api/lingxing/fbaStock';
import { FbaStockVO, FbaStockQuery, FbaStockForm } from '@/api/lingxing/fbaStock/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const fbaStockList = ref<FbaStockVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const fbaStockFormRef = ref<ElFormInstance>();
const newestUpdateTime = ref('');

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: FbaStockForm = {
  id: undefined,
  wname: undefined,
  name: undefined,
  sid: undefined,
  asin: undefined,
  productName: undefined,
  productImage: undefined,
  msku: undefined,
  fnsku: undefined,
  sku: undefined,
  categoryName: undefined,
  categoryId: undefined,
  brandName: undefined,
  brandId: undefined,
  stockCostTotal: undefined,
  cost: undefined,
  shareType: undefined,
  afnFulfillableQuantity: undefined,
  reservedFcTransfers: undefined,
  reservedFcProcessing: undefined,
  reservedCustomerorders: undefined,
  totalFulfillableQuantity: undefined,
  afnUnsellableQuantity: undefined,
  afnInboundWorkingQuantity: undefined,
  afnInboundShippedQuantity: undefined,
  afnInboundReceivingQuantity: undefined,
  afnErpRealShippedQuantity: undefined,
  afnResearchingQuantity: undefined,
  invAge0To30Days: undefined,
  invAge31To60Days: undefined,
  invAge61To90Days: undefined,
  invAge0To90Days: undefined,
  invAge91To180Days: undefined,
  invAge181To270Days: undefined,
  invAge271To330Days: undefined,
  invAge331To365Days: undefined,
  invAge271To365Days: undefined,
  invAge365PlusDays: undefined,
  fulfillmentChannelName: undefined
};
const data = reactive<PageData<FbaStockForm, FbaStockQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    wname: undefined,
    name: undefined,
    sid: undefined,
    asin: undefined,
    productName: undefined,
    productImage: undefined,
    msku: undefined,
    fnsku: undefined,
    sku: undefined,
    categoryName: undefined,
    categoryId: undefined,
    brandName: undefined,
    brandId: undefined,
    stockCostTotal: undefined,
    cost: undefined,
    shareType: undefined,
    afnFulfillableQuantity: undefined,
    reservedFcTransfers: undefined,
    reservedFcProcessing: undefined,
    reservedCustomerorders: undefined,
    totalFulfillableQuantity: undefined,
    afnUnsellableQuantity: undefined,
    afnInboundWorkingQuantity: undefined,
    afnInboundShippedQuantity: undefined,
    afnInboundReceivingQuantity: undefined,
    afnErpRealShippedQuantity: undefined,
    afnResearchingQuantity: undefined,
    invAge0To30Days: undefined,
    invAge31To60Days: undefined,
    invAge61To90Days: undefined,
    invAge0To90Days: undefined,
    invAge91To180Days: undefined,
    invAge181To270Days: undefined,
    invAge271To330Days: undefined,
    invAge331To365Days: undefined,
    invAge271To365Days: undefined,
    invAge365PlusDays: undefined,
    fulfillmentChannelName: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    wname: [{ required: true, message: '仓库名称不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '仓库名称【同wname】不能为空', trigger: 'blur' }],
    sid: [{ required: true, message: '店铺id不能为空', trigger: 'blur' }],
    asin: [{ required: true, message: 'ASIN不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '品名不能为空', trigger: 'blur' }],
    productImage: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
    msku: [{ required: true, message: 'MSKU不能为空', trigger: 'blur' }],
    fnsku: [{ required: true, message: 'FNSKU不能为空', trigger: 'blur' }],
    sku: [{ required: true, message: 'SKU不能为空', trigger: 'blur' }],
    categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    categoryId: [{ required: true, message: '分类Id不能为空', trigger: 'blur' }],
    brandName: [{ required: true, message: '品牌名称不能为空', trigger: 'blur' }],
    brandId: [{ required: true, message: '品牌id不能为空', trigger: 'blur' }],
    stockCostTotal: [{ required: true, message: '货值不能为空', trigger: 'blur' }],
    cost: [{ required: true, message: '库存成本不能为空', trigger: 'blur' }],
    shareType: [{ required: true, message: '共享类型不能为空', trigger: 'change' }],
    afnFulfillableQuantity: [{ required: true, message: '可售不能为空', trigger: 'blur' }],
    reservedFcTransfers: [{ required: true, message: '待调仓不能为空', trigger: 'blur' }],
    reservedFcProcessing: [{ required: true, message: '调仓中不能为空', trigger: 'blur' }],
    reservedCustomerorders: [{ required: true, message: '待发货不能为空', trigger: 'blur' }],
    totalFulfillableQuantity: [{ required: true, message: '总可用库存：可售+待调仓+调仓中不能为空', trigger: 'blur' }],
    afnUnsellableQuantity: [{ required: true, message: '不可售不能为空', trigger: 'blur' }],
    afnInboundWorkingQuantity: [{ required: true, message: '计划入库不能为空', trigger: 'blur' }],
    afnInboundShippedQuantity: [{ required: true, message: '在途不能为空', trigger: 'blur' }],
    afnInboundReceivingQuantity: [{ required: true, message: '入库中不能为空', trigger: 'blur' }],
    afnErpRealShippedQuantity: [{ required: true, message: '实际在途不能为空', trigger: 'blur' }],
    afnResearchingQuantity: [{ required: true, message: '调查中数量不能为空', trigger: 'blur' }],
    invAge0To30Days: [{ required: true, message: '0-1个月库龄不能为空', trigger: 'blur' }],
    invAge31To60Days: [{ required: true, message: '1-2个月库龄不能为空', trigger: 'blur' }],
    invAge61To90Days: [{ required: true, message: '2-3个月库龄不能为空', trigger: 'blur' }],
    invAge0To90Days: [{ required: true, message: '0-3个月库龄不能为空', trigger: 'blur' }],
    invAge91To180Days: [{ required: true, message: '3-6个月库龄不能为空', trigger: 'blur' }],
    invAge181To270Days: [{ required: true, message: '6-9个月库龄不能为空', trigger: 'blur' }],
    invAge271To330Days: [{ required: true, message: '9-11个月库龄不能为空', trigger: 'blur' }],
    invAge331To365Days: [{ required: true, message: '11-12个月库龄不能为空', trigger: 'blur' }],
    invAge271To365Days: [{ required: true, message: '9-12个月库存不能为空', trigger: 'blur' }],
    invAge365PlusDays: [{ required: true, message: '12个月以上库龄不能为空', trigger: 'blur' }],
    fulfillmentChannelName: [{ required: true, message: '配送方式不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询领星FBA库存列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFbaStock(queryParams.value);
  fbaStockList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  const res1 = await getNewestUpdateTime();
  newestUpdateTime.value = res1.msg;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  fbaStockFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: FbaStockVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加领星FBA库存';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: FbaStockVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getFbaStock(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改领星FBA库存';
};

/** 提交按钮 */
const submitForm = () => {
  fbaStockFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateFbaStock(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addFbaStock(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: FbaStockVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除领星FBA库存编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delFbaStock(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'lingxing/fbaStock/export',
    {
      ...queryParams.value
    },
    `fbaStock_${new Date().getTime()}.xlsx`
  );
};

/** 同步数据按钮操作 */
const handleSyncData = async (row?: FbaStockVO) => {
  loading.value = true;
  await proxy?.$modal.confirm('是否同步领星数据项？').finally(() => (loading.value = false));
  loading.value = true;
  await syncData().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('同步数据成功!');
  loading.value = true;
  await getList().finally(() => (loading.value = false));
};

onMounted(() => {
  getList();
});
</script>
